# -*- coding: utf-8 -*-
"""
Created on Wed Sep 10 21:55:40 2014

@author: Magda
"""

from collections import OrderedDict
import csv
import matplotlib.pyplot as plt
import matplotlib.dates as mpld
import datetime
import scipy.optimize as optimization
import numpy 

class_data = OrderedDict()
filename = "TransportData.txt"
with open(filename, 'rb') as f:
    reader = csv.reader(f, delimiter='\t')
    for row in reader:
        curr_date = datetime.datetime.strptime(row[0] + ' ' + row[1], "%d-%m-%Y %H:%M")
        class_data[curr_date] = row[2]
        
scan_data = OrderedDict()
filename = "1b768f942564005168dda562defa5b_1410774213.bigdata"
with open(filename, 'rb') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        if row[3] != 'timestamp':
            curr_date = datetime.datetime.fromtimestamp(int(row[3]))
            if scan_data.has_key(row[7]):
                
                scan_data[row[7]] = scan_data[row[7]] + [(curr_date, row[2])]
            else:
                scan_data[row[7]] = [(curr_date, row[2])]
           
scan_data.pop("ssid", None)           

dates = []
for item in scan_data.values():
    dates = dates + [i[0] for i in item]

dates = set(dates)

for key in scan_data.keys():
    curr_dates = [i[0] for i in scan_data[key]]
    for single_date in dates:
        if(single_date not in curr_dates):
            scan_data[key] = scan_data[key] + [(single_date, float('nan'))]

def plot_figure(data, from_date, end_date, figname):
    fig = plt.figure(figsize=(50, 50))
    ax = plt.gca() 
    for item in data.values():
        sorted_data = sorted(item, reverse = True, key=lambda x: x[0])
        filtered_data = []
        for item in sorted_data:
            if item[0] >= from_date and item[0] <= end_date:
                filtered_data.append(item)
            
        ax.plot([i[0] for i in filtered_data], [i[1] for i in filtered_data])
    plt.savefig(figname)       
    plt.close(fig)
   
plot_figure(scan_data, min(dates), max(dates), "all_data.png")

#for i in xrange(0,len(class_data.items()) - 1):
#    plot_figure(scan_data, class_data.items()[i][0], class_data.items()[i+1][0], class_data.items()[i][1] + class_data.items()[i][0].strftime("%d-%m-%Y-%H%M"))
#plot_figure(scan_data, 1410283380, 1410283980, "bike1410283380.png")
#plot_figure(scan_data, 1410285600, 1410286020, "bike1410285600.png")
    